import _ from 'lodash';
import { Request, Response, NextFunction } from 'express';
import { getActors, createActor, deleteActor, getByIdActor, updateActor, getActorsById } from './actor.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo;
  let pageSize = request.query.pageSize
  let sex = request.query.sex;
  let nationality = request.query.nationality;
  let keyWord = request.query.keyWord;
  const data = await getActors(parseInt(`${pageNo}`), parseInt(`${pageSize}`), parseInt(`${sex}`, 10), parseInt(`${nationality}`, 10), keyWord as any);

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const actorDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getByIdActor(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取演员 (按 ID 获取)
 */
export const actors = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.body;

  let postIdArr = postId.split(",").map(Number);

  // 调取内容
  try {
    let dataArr = [];
    for (let i of postIdArr) {
      if (i > 0) {
        const data = await getActorsById(parseInt(i, 10));
        dataArr.push(data[0]);
      }
    }

    // 做出响应
    response.send(dataArr);
  } catch (error) {
    next(error);
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let actorsModel = request.body;

  // 添加更改时间
  let changeTime = Math.floor(new Date().getTime())
  actorsModel.changeTime = changeTime;
  
  // 创建内容
  try {

    if (actorsModel.id && actorsModel.id > 0) {
      const data = await updateActor(actorsModel, parseInt(actorsModel.id));
      response.send(data);
    } else {
      const data = await createActor(actorsModel);
      response.send(data);
    }
    
  } catch (error) {
    next(error);
  }
}


/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除内容
  try {
    const data = await deleteActor(parseInt(postId, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
};


